package com.calvin.springcloud.config;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.calvin.springcloud.base.ResponseResult;

import lombok.extern.slf4j.Slf4j;

@ControllerAdvice
@Slf4j
public class GlobalControllerExceptionHandler {
	
	private static final String AJAX_TPYE= "XMLHttpRequest";

	@ExceptionHandler(Exception.class)
	@ResponseBody
	public Object defaultExceptionHandler(HttpServletRequest request, Exception e) {
		String code = "";
		String message = "";
		
		//if (e instanceof ValidatorException){
			//log.error("校验异常信息：["+ code + "]" + message);
		//} else if(e instanceof BusinessErrorException){
			//log.error("业务异常信息：[" + code + "]" + message);
		//} else if(e instanceof BusinessWarningException){
			//log.error("警告信息：[" + code + "]" + message);
		//} 
		message = "系统异常：" + e.getMessage();
		log.error("系统异常信息：", e);
		//处理异步请求异常返回
		if(AJAX_TPYE.equals(request.getHeader("X-Requested-With"))){
			return new ResponseResult<Object>().fail(message);
		} else {
			ModelAndView modelAndView = new ModelAndView();
			modelAndView.getModelMap().addAttribute("errorCode", code);
			modelAndView.getModelMap().addAttribute("errorMsg", message);
			modelAndView.setViewName("error");
			return modelAndView;
		}
	}

}
